Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

151
Views
Why is my line not breaking when I use "\n" in react?

I am trying to use this hook:

useEffect(() => {
  var arrText = txt.split('*');
  arrText.map((line, index) =>
    setTimeout(() => {
      setTexto((prev) => {
        return (prev += line + '\n');
      });
    }, 300 * index),
  );
}, []);

And it simply rejects my \n and if I try to return JSX (the line in a paragraph), it becomes a [object object]

Can you please help me? <3

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

The problem is, unless you're trying to display a newline in a pre tag, it will be ignored in the browser. You could however store the text content in the state in an array, update that using the setTimeout and render this state. You can use <p> tags or <br> tags to display the text on new lines.

Also, you shouldn't use map() as it creates a new array. You could use forEach() or a simple for loop instead.

let txt =
  'Lorem ipsum, dolor sit amet consectetur adipisicing elit. Tenetur sapiente incidunt molestias beatae voluptas fuga repellendus sit nihil voluptate laudantium delectus aliquam, nulla non suscipit a ea natus voluptatem distinctio!';

function App() {
  let [texto, setTexto] = React.useState([]);

  React.useEffect(() => {
    txt.split(' ').forEach((line, index) =>
      setTimeout(() => {
        setTexto((prev) => {
          return [...prev, line];
        });
      }, 300 * index)
    );
  }, []);

  return (
    <div>
      {texto.map((word, i) => (
        <p key={i}>{word}</p>
      ))}
    </div>
  );
}

ReactDOM.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>,
  document.getElementById('root')
);
<div id="root"></div>
<script src="https://unpkg.com/react/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom/umd/react-dom.production.min.js"></script>

You shouldn't store HTML tags in your state as you will need to use dangerouslySetInnerHTML.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!